package com.lightsh.mapdemo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.ItemizedOverlay.OnFocusChangeListener;
import com.lightsh.util.Utility;
import com.meizu.overlaymanager.ManagedOverlay;
import com.meizu.overlaymanager.OverlayManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ReceiverCallNotAllowedException;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.TrafficStats;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;

public class MainActivity extends MapActivity {
	
	private static final String TAG = "MyMapDemo";
	private static final boolean DEBUG = true;
	
	private MapView mMapView;
	private MapController mMapControl;
	private LocationManager mLocationManager;
	private LocationListener mLocationListener;
	private OverlayManager mOverlayManager;
	private List<ScanResult> mWifiList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        mMapView = (MapView)findViewById(R.id.MapView);
        mMapView.setBuiltInZoomControls(true);
        mMapView.setClickable(true);
        mMapControl = mMapView.getController();
        mMapControl.setZoom(17);
        
        mOverlayManager = new OverlayManager(this, mMapView);
        
        mLocationListener = new LocationListener() {
			
			public void onStatusChanged(String provider, int status, Bundle extras) {
				Log.d(TAG, "onStatusChanged:" + provider);
			}
			
			public void onProviderEnabled(String provider) {
				Log.d(TAG, "onProviderEnabled:" + provider);
				
			}
			
			public void onProviderDisabled(String provider) {
				Log.d(TAG, "onProviderDisabled:" + provider);
				
			}
			
			public void onLocationChanged(Location location) {
				Log.d(TAG, "onLocationChanged:" + location);
				if(location != null){
					Toast.makeText(MainActivity.this, "lat:" + location.getLatitude() + ",lng:" + location.getLongitude(), Toast.LENGTH_LONG).show();
				}
				refreshMapViewByGeoPoint(getGeoByLocation(location), mMapView, 10, false);
				
			}
		};
		
		mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, mLocationListener);
        
		
//		Location location = getLocationProvider();
//		if(location == null){
//			Toast.makeText(this, "getLocation error!", Toast.LENGTH_LONG).show();
//		}else{
//			refreshMapViewByGeoPoint(getGeoByLocation(location), mMapView, 17, false);
//		}
		
		
		
		registerReceiver(mWifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
		WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
		wm.startScan();
		
		MyItemizedOverlay itemOverlay = new MyItemizedOverlay(getResources().getDrawable(R.drawable.icon));
		itemOverlay.setOnFocusChangeListener(mFocusChangeListener);
		
		GeoPoint gp = new GeoPoint(22374938, 113561159);		
		itemOverlay.addOverlayItem(new MyOverlayItem(gp, "mytitle", "mysnippet"));		
		mMapView.getOverlays().add(itemOverlay);
		mMapControl.animateTo(gp);
		
		checkAndOpenGPS();
    }
    
    private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			mWifiList = ((WifiManager)getSystemService(Context.WIFI_SERVICE)).getScanResults();
		}
	};
    
    public void onDestroy(){
    	mLocationManager.removeUpdates(mLocationListener);
    	unregisterReceiver(mWifiReceiver);
    	super.onDestroy();
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	
	public Location getLocationProvider(){
		Location location = null;
		try{
			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			criteria.setPowerRequirement(Criteria.POWER_HIGH);
			String strLocationProvider = mLocationManager.getBestProvider(criteria, true);
			location = mLocationManager.getLastKnownLocation(strLocationProvider);
		}catch(Exception e){
			e.printStackTrace();
		}
		return location;
	}
	
	/**
	 * 
	 * @param location
	 * @category 根据location获取GeoPoint
	 */
	private GeoPoint getGeoByLocation(Location location){
		GeoPoint gp = null;
		try{
			if(location != null){
				double geoLatitude = (int)location.getLatitude()*1E6;
				double geoLongitude = (int)location.getLongitude()*1E6;
				gp = new GeoPoint((int)geoLatitude, (int)geoLongitude);
			}else{
				Log.e(TAG, "getGeoByLocation:location is null");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return gp;
	}
	
	/**
	 * 
	 * @param gp
	 * @return 地址字符串
	 */
	public List<Address> getAddressByGeoPoint(GeoPoint gp){
		List<Address> listAddress = null;
		try{
			if(gp != null){
				Geocoder gc = new Geocoder(this, Locale.getDefault());
				double geoLatitude = (int)gp.getLatitudeE6()/1E6;
				double geoLongitude = (int)gp.getLongitudeE6()/1E6;
				
				listAddress = gc.getFromLocation(geoLatitude, geoLongitude, 1);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return listAddress;
	}
	
	/**
	 * 
	 * @param gp
	 * @param mv
	 * @param zoomLevel
	 * @param bIfSatellite
	 * @category 根据输入参数更新mapView
	 * 
	 */
	public static void refreshMapViewByGeoPoint(GeoPoint gp, MapView mv, int zoomLevel, boolean bIfSatellite){
		try{
			mv.displayZoomControls(true);
			MapController mc = mv.getController();
			mc.animateTo(gp);
			mc.setZoom(zoomLevel);
			if(bIfSatellite){
				mv.setSatellite(true);
				mv.setStreetView(true);
			}else{
				mv.setSatellite(false);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public GeoPoint getLocation(){
		return Utility.getLocationByCellAndWifi(this, mWifiList);
	}
	
	public void createSimpleOverlay(GeoPoint gp) {
		ManagedOverlay managedOverlay = mOverlayManager.createOverlay("simpleOverlay");
		managedOverlay.createItem(gp, "Item");
		mOverlayManager.populate();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "网络");
		menu.add(0, 1, 1, "wifi");
		menu.add(0, 2, 2, "sim卡");
		menu.add(0, 3, 3, "BestProvider");
		menu.add(0, 4, 4, "gps");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		GeoPoint gp = null;
		switch(item.getItemId()){
		case 0:{
			gp = getLocation();
		}
			break;
		case 1:{
			gp = getGeoByLocation(mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
		}
			break;
		case 2:
			gp = getGeoByLocation(mLocationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER));
			break;
		case 3:
			gp = getGeoByLocation(getLocationProvider());
			break;
		case 4:{
			gp = getGeoByLocation(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
		}
			break;
		}
		if(gp != null){
			Log.e(TAG, "" + gp);
			createSimpleOverlay(gp);
			mMapControl.animateTo(gp);
			mMapControl.setZoom(17);
		}else{
			Toast.makeText(MainActivity.this, "location null", Toast.LENGTH_SHORT).show();
		}
		return super.onOptionsItemSelected(item);
	}
	
	private OnFocusChangeListener mFocusChangeListener = new OnFocusChangeListener() {

		public void onFocusChanged(ItemizedOverlay overlay, OverlayItem newFocus) {
			// TODO Auto-generated method stub
			Toast.makeText(MainActivity.this, "onFocusChanged:" + newFocus.getTitle(), 2000).show();
			
		}
	};
	
	private void checkAndOpenGPS(){
		if(!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
			Log.d(TAG, "try open gps");
			// 前面2种方法在某些手机上面没有权限
//			Intent gpsIntent = new Intent();
//			gpsIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
//			gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
//			gpsIntent.setData(Uri.parse("custom:3"));
//			try {
//				PendingIntent.getBroadcast(this, 0, gpsIntent, 0).send();
//			}catch (CanceledException e) {
//				e.printStackTrace();
//			}
			
//			Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, true);
			
			Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);        
			startActivityForResult(intent,0);
		}
	}
	
}